#include "../include/login.h"
#include "../Ui_set/ui_login.h"
#include"../include/register.h"
#include<QMessageBox>
#include<QDir>

Login::Login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    this->setWindowTitle(tr("QQ"));
    this->setWindowIcon(QIcon(QPixmap("://images/qq.png")));

    ui->account->setFocus();
    QRegularExpressionValidator *account_rev=new QRegularExpressionValidator(QRegularExpression("^\\d{9}$"));
    ui->account->setValidator(account_rev);
    QRegularExpressionValidator *password_rev=new QRegularExpressionValidator(QRegularExpression("^[\\w]{6,16}$"));
    ui->password->setValidator(password_rev);
    ui->password->setPlaceholderText(tr("6~16位，包含大小写字母和数字"));

    connect(ui->loginBtn,SIGNAL(clicked(bool)),this,SLOT(clickLoginBtn()));
    connect(ui->registerBtn,SIGNAL(clicked(bool)),this,SLOT(clickRegisteBtn()));
    connect(ui->quitBtn,SIGNAL(clicked()),this,SLOT(close()));
}

Login::~Login()
{
    delete ui;
}

void Login::clickLoginBtn()
{
    loginAccount=ui->account->text();
    loginPassword=ui->password->text();
    if(loginAccount.isEmpty()||loginPassword.isEmpty()){
        QMessageBox::critical(this,tr("警告！"),tr("账号或密码输入为空！"),QMessageBox::Cancel);
        return;
    }
    if(!this->judgePassword()){
        QMessageBox::critical(this,tr("警告！"),tr("账号密码输入不正确！"),QMessageBox::Cancel);
        return;
    }
    this->accept();
}

void Login::clickRegisteBtn()
{
    Register *registe=new Register;
    registe->show();
}

const bool Login::judgeAccount()
{
    QFile *acFile=new QFile("Account.txt");
    acFile->open(QFile::ReadOnly);
    while(!acFile->atEnd()){
        QByteArray line_byte=acFile->readLine();
        QString line_str=QString::fromUtf8(line_byte);
        if(line_str==loginAccount){
            acFile->close();
            return true;
        }
    }
    acFile->close();
    return false;
}

const bool Login::judgePassword()
{
    if(this->judgeAccount()==false) return false;
    QDir info_folder_dir(loginAccount);
    if(info_folder_dir.exists()){
        QFile *pwFile=new QFile(loginAccount+"/Password.txt");
        pwFile->open(QFile::ReadOnly);
        while(!pwFile->atEnd()){
            QByteArray line_byte=pwFile->readLine();
            QString line_str=QString::fromUtf8(line_byte);
            if(line_str==loginPassword){
                pwFile->close();
                return true;
            }
        }
        pwFile->close();
        return false;
    }
    return false;
}
